# 代码形式根新参数

import rclpy

from rclpy.node import Node

from rcl_interfaces.srv import SetParameters
from rcl_interfaces.msg import Parameter,ParameterValue,ParameterType
class ParamSet(Node):
    def __init__(self,node_name):
        super().__init__(node_name)
        self.get_logger().info(f"{node_name} 启动")

    # 调用服务修改参数值 参数是基于服务的
    def call_set_parameters(self,parameters):
        update_param=self.create_client(SetParameters,'/param_test/set_parameters')
        # 1
        while update_param.wait_for_service(timeout_sec=1.0) is False:
            self.get_logger().info("等待参数根新服务上线")
        # 2
        # 2 构造request
        request=SetParameters.Request()
        request.parameters=parameters
       
        # 调用服务根新参数
        future=update_param.call_async(request)
        rclpy.spin_until_future_complete(self,future)
        response=future.result()

        return response
    
    # 构造parameters根新参数
    def update_params(self,param_name="他马的"):
        # 1 创建参数对象 只是一个参数
        param=Parameter()
        param.name="param_name" # 参数名字

        # 2. 创建param_value
        param_value=ParameterValue()
        param_value.string_value=param_name # 使用ros2 interface show rcl_interfaces/srv/SetParameters命令查看参数有那些类型
        param_value.type=ParameterType.PARAMETER_STRING
        param.value=param_value

        # 3 请求根新参数
        response=self.call_set_parameters([param])
        for result in response.results:
            self.get_logger().info(f"设置参数结果:{result.successful} {result.reason}")


def main():
    rclpy.init()
    node=ParamSet('param_set')
    node.update_params()
    rclpy.spin(node)

    rclpy.shutdown()